package com.cykj.order.controller;
import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.domain.AlipayTradePagePayModel;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.cykj.order.config.AliPayConfig;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @BelongsProject: RuoYi-Vue
 * @BelongsPackage: com.ruoyi.controller
 * @Author: 泽日
 * @CreateTime: 2025-08-21 10:38
 * @Description: TODO
 * @Version: 1.0
 */
@RestController
@RequestMapping("/alipay")
public class AliPayController {

    @Resource
    private AliPayConfig aliPayConfig;

    @RequestMapping("/notify")
    public String notify(HttpServletRequest request) throws AlipayApiException {
        // 获取支付宝POST过来的参数
        Map<String, String> params = new HashMap<>();
        // 获取所有参数（Map<String, String[]>）
        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            StringBuilder valueStr = new StringBuilder();
            for (int i = 0; i < values.length; i++) {
                valueStr.append(i == values.length - 1 ? values[i] : values[i] + ",");
            }
            // 将参数封装成 Map<String, String>，用于验签
            params.put(name, valueStr.toString());
        }

        // 支付宝验签，验证回调参数是否被篡改
        boolean signVerified = AlipaySignature.rsaCheckV1(
                params,
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getCharset(),
                aliPayConfig.getSignType()
        );
        System.err.println("成功回调");

        if (signVerified) {
            // 验签成功，处理业务逻辑
            // 获取商户订单号（你系统中的订单号
            String outTradeNo = params.get("out_trade_no");
            // 获取交易状态
            String tradeStatus = params.get("trade_status");
            // 判断是否支付成功（TRADE_SUCCESS：支付成功，TRADE_FINISHED：交易结束，不可退款）
            if ("TRADE_SUCCESS".equals(tradeStatus) || "TRADE_FINISHED".equals(tradeStatus)) {
                System.out.println("支付成功，订单号：" + outTradeNo);
                // 充值订单
                if (outTradeNo.startsWith("RECHARGE")) {

                }
                // 支付订单
                if (outTradeNo.startsWith("ORDER")) {

                }
            }
            return "success";
        } else {
            System.err.println("支付宝签名验证失败！");
            return "fail";
        }
    }


    @RequestMapping("/payBalance")
    public Map<String, Object> payBalance(@RequestBody Map<String, String> params) throws Exception {
        String amount = params.get("amount");
        String userId = params.get("userId");

        AlipayClient alipayClient = new DefaultAlipayClient(
                aliPayConfig.getGatewayUrl(),
                aliPayConfig.getAppId(),
                aliPayConfig.getAppPrivateKey(),
                "json",
                aliPayConfig.getCharset(),
                aliPayConfig.getAlipayPublicKey(),
                aliPayConfig.getSignType()
        );
        Map<String, Object> result = new HashMap<>();
        String orderNo = "RECHARGE" + System.currentTimeMillis();


        // 使用PC网页支付模型
        AlipayTradePagePayModel model = new AlipayTradePagePayModel();
        model.setOutTradeNo(orderNo);
        model.setTotalAmount(amount);
        model.setSubject("充值账单");
        model.setProductCode("FAST_INSTANT_TRADE_PAY");

        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        request.setReturnUrl(aliPayConfig.getReturnUrl());
        request.setNotifyUrl(aliPayConfig.getNotifyUrl());
        request.setBizModel(model);

        AlipayTradePagePayResponse response = alipayClient.pageExecute(request, "POST");
        if (response.isSuccess()) {
            result.put("success", true);
            result.put("payHtml", response.getBody());
        } else {
            result.put("success", false);
            result.put("msg", "支付请求失败");
        }

        return result;
    }
}
